import copy
import logging
from datetime import datetime

from airflow.models.idata_datasource import Datasource
from airflow.models.idata_project import Project
from airflow.models.idata_project_datasource import ProjectDatasource
from airflow.utils.session import provide_session

log = logging.getLogger(__name__)


@provide_session
def add_datasource(datasource_type, name, ip, port, user_name, password, project_ids, oa_user_name, session=None):
    datasource = Datasource(name=name, type=datasource_type, ip=ip, port=port, user_name=user_name, password=password, oa_user_name=oa_user_name, create_time=datetime.now())
    Datasource.add_datasource(datasource)
    for project_id in project_ids:
        project_datasource = ProjectDatasource(project_id=project_id, datasource_id=datasource.id)
        ProjectDatasource.add_project_datasource(project_datasource)


@provide_session
def delete_datasource(datasource_id, session=None):
    Datasource.delete_datasource(datasource_id, session)
    ProjectDatasource.delete_project_datasource(None, datasource_id, session)


@provide_session
def get_datasources(page, project_id, datasource_type, session=None):
    if page == 0:
        datasources = Datasource.get_datasources(project_id, datasource_type, session)
        map_datasources = map(Datasource.to_json, datasources)
        result = list(map_datasources)
        for datasource in result:
            projects = Project.get_datasource_project(datasource['id'])
            map_projects = map(Project.to_json, projects)
            datasource['projects'] = list(map_projects)
        return result
    else:
        datasources_result = Datasource.get_datasources_page(page, project_id, datasource_type, session)
        datasources_result.items = list(map(Datasource.to_json, datasources_result.items))
        for datasource in datasources_result.items:
            projects = Project.get_datasource_project(datasource['id'])
            map_projects = map(Project.to_json, projects)
            datasource['projects'] = list(map_projects)
        result = datasources_result.to_json()
        return result


@provide_session
def update_datasource(datasource_id, datasource_type, name, ip, port, user_name, password, project_ids, oa_user_name, session=None):
    datasource = Datasource(id=datasource_id, name=name, type=datasource_type, ip=ip, port=port, user_name=user_name,
                    password=password, oa_user_name=oa_user_name, create_time=datetime.now())
    Datasource.update_datasource(datasource, session)
    ProjectDatasource.delete_project_datasource(None, datasource_id, session)
    for project_id in project_ids:
        project_datasource = ProjectDatasource(project_id=project_id, datasource_id=datasource_id)
        ProjectDatasource.add_project_datasource(project_datasource, session)
